package com.javaee.wordtree.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.javaee.wordtree.entity.Word;
import com.javaee.wordtree.entity.User;
import com.javaee.wordtree.entity.MmryRecord;
import com.javaee.wordtree.mapper.WordMapper;
import com.javaee.wordtree.mapper.UserMapper;
import com.javaee.wordtree.mapper.MmryRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class WordService {

    @Resource
    private WordMapper wordMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private MmryRecordMapper mmryRecordMapper;

    /**
     * 根据单词文本搜索单词信息
     * 
     * @param wordText 单词文本
     * @param userID   用户ID（可选）
     * @return 单词信息，包含翻译、短语、例句等
     */
    public Word searchWord(String wordText, String userID) {
        log.info("搜索单词: {}, 用户ID: {}", wordText, userID);

        // 根据单词文本查找单词
        Word word = wordMapper.findWordByText(wordText);

        if (word == null) {
            log.info("未找到单词: {}", wordText);
            return null;
        }

        // 如果提供了用户ID，获取用户的学习记录
        if (userID != null && !userID.trim().isEmpty()) {
            try { // 获取用户信息
                User user = userMapper.selectOne(
                        Wrappers.<User>lambdaQuery()
                                .eq(User::getUserID, userID));

                if (user != null) {
                    // 获取用户对该单词的记忆记录
                    MmryRecord memoryRecord = mmryRecordMapper.selectOne(
                            Wrappers.<MmryRecord>lambdaQuery()
                                    .eq(MmryRecord::getUserID, userID)
                                    .eq(MmryRecord::getWordID, word.getWordID()));

                    if (memoryRecord != null) {
                        // 设置用户的陌生度
                        word.setStrangeDegree(memoryRecord.getStrange());
                        log.info("用户 {} 对单词 {} 的陌生度: {}", userID, wordText, memoryRecord.getStrange());
                    } else {
                        // 用户未学过该单词，设置默认陌生度
                        word.setStrangeDegree(5); // 最高陌生度
                        log.info("用户 {} 未学过单词 {}", userID, wordText);
                    }

                    // 检查单词是否属于用户的目标词书
                    if (!word.getBelongBook().equals(user.getTargetBook())) {
                        log.info("单词 {} 不属于用户 {} 的目标词书", wordText, userID);
                    }
                } else {
                    log.warn("用户不存在: {}", userID);
                }
            } catch (Exception e) {
                log.error("获取用户学习记录失败: {}", e.getMessage(), e);
            }
        }

        log.info("成功搜索到单词: {}, 包含 {} 个翻译, {} 个短语, {} 个例句",
                wordText,
                word.getTranslations() != null ? word.getTranslations().size() : 0,
                word.getPhrases() != null ? word.getPhrases().size() : 0,
                word.getSentences() != null ? word.getSentences().size() : 0);

        return word;
    }

    /**
     * 检查单词是否存在
     * 
     * @param wordText 单词文本
     * @return 是否存在
     */
    public boolean wordExists(String wordText) {
        if (wordText == null || wordText.trim().isEmpty()) {
            return false;
        }

        Long count = wordMapper.selectCount(
                Wrappers.<Word>lambdaQuery()
                        .eq(Word::getWord, wordText.trim().toLowerCase()));

        return count != null && count > 0;
    }

    /**
     * 根据单词文本获取单词ID
     * 
     * @param wordText 单词文本
     * @return 单词ID，如果不存在返回null
     */
    public Integer getWordIdByText(String wordText) {
        if (wordText == null || wordText.trim().isEmpty()) {
            return null;
        }

        Word word = wordMapper.selectOne(
                Wrappers.<Word>lambdaQuery()
                        .eq(Word::getWord, wordText.trim().toLowerCase())
                        .select(Word::getWordID));

        return word != null ? word.getWordID() : null;
    }
}
